const STYLET_YPE = {
  bars: 0,
  candles: 1,
  hollowCandles: 9,
  heikinAshi: 8,
  line: 2,
  area: 3,
  baseline: 10
};

export class TlTvApi {
  constructor(props) {
    this.widget = null;
    this.$ = null;
    this.doc = null;
    //tradingview 模型层
    this.model = null;

    if (!props.widget) {
      throw "请传入tradingview widget实例";
    }
    this.widget = props.widget;
    this.$ = this.widget._innerWindow().$;
    this.doc = this.widget._innerWindow().document;
    this.model = this.widget
      ._innerWindow()
      .headerWidget._model.model()
      .properties();
  }

  afterFn(fn, afterFn) {
    return function() {
      fn.apply(this, arguments);
      const ret = afterFn.apply(this, arguments);
      return ret;
    };
  }
}

export class Widget extends TlTvApi {
  constructor(props) {
    super(props);
    this.chart = null;
    this.chart = this.getChartIns();
  }
  getChartIns() {
    return this.widget.activeChart();
  }
}

export class Chart extends Widget {
  constructor(props) {
    super(props);
  }
}

export class PanelWidgets extends Chart {
  constructor(props) {
    super(props);
    this.panelWidgets = null;
    this.panelWidgets = this.getPanelWidgetsIns();
  }

  getPanelWidgetsIns() {
    return this.chart._chartWidget.paneWidgets()[0];
  }
}

// export class PanelStatusWidget extends PanelWidgets {
//   constructor(props) {
//     super(props);
//     this.panelStatusWidget = null;
//     this.init();
//   }

//   init() {
//     this.panelStatusWidget = this.getPanelStatusWidget();
//   }

//   getPanelStatusWidget() {
//     return this.panelWidgets.statusWidget();
//   }

//   togglePanelStatusWidget() {
//     this.panelStatusWidget.toggleTitles();
//   }
// }

export class PanelHeader extends TlTvApi {
  constructor(props) {
    super(props);
    this.opts = props.opts;
    this.toggleColor();
    this.showHeaderLeft();

    this.dom = {
      right: null,
      left: null,
      el: null,
      img: null,
      btn: [],
      menu: [],
      timeShareBtn: null
    };

    //MA线
    this.ma = [];

    this.timer = null;
    this.panelHeaderIns = this.getPanelHeaderIns();
    this.widgetStyle = new WidgetStyle({ panelHeaderIns: this.panelHeaderIns });

    this.init();
  }

  init() {
    this.initMa();
    this.initDom();
    this.addListen();
    this.render();
    this.rmMenuClose();
    this.showMenu();
  }

  showHeaderLeft() {
    this.$(".chart-page .header-chart-panel-content .left").css(
      "visibility",
      "visible"
    );
  }

  toggleColor() {
    if (this.opts.isLight) {
      this.$(".chart-page").addClass("light");
    }
  }

  initMa() {
    this.ma = [
      this.widget.chart().createStudy("Moving Average", false, false, [5]),
      this.widget.chart().createStudy("Moving Average", false, false, [10]),
      this.widget.chart().createStudy("Moving Average", false, false, [30]),
      this.widget.chart().createStudy("Moving Average", false, false, [60])
    ];
  }

  initDom() {
    this.dom.el = this.panelHeaderIns._$root;
    this.dom.right = this.panelHeaderIns._$right;
    this.dom.left = this.panelHeaderIns._$left;
    this.dom.menu = this.panelHeaderIns._interval._e.find(".quick span");

    // time share

    const timeShare = this.widget
      .createButton({ align: "left" })
      .attr("title", "Line")
      .attr("domTimeShare", "true")
      .attr("style", "width:47px;text-align:center")
      .append(this.$("<span>Line</span>"));
    this.dom.timeShareBtn = timeShare[0];

    // this.dom.menu[this.dom.menu.length - 1].tldata = {
    //   //分时
    //   type: "area"
    // };

    // const i18n = {
    //   en: "Line",
    //   zh: "分时",
    //   ja: "分時間"
    // };
    // this.dom.menu.last().attr("title", i18n["en"]);
    // this.dom.timeShareBtn = this.dom.menu.last()[0];
  }

  isTimeShare(dom) {
    return dom && dom.tldata && dom.tldata.type == "area";
  }

  getPanelHeaderIns() {
    return this.widget._innerWindow().headerWidget;
  }

  getDataSources() {
    return this.widget.chart()._chartWidget._model.dataSources();
  }

  delMa() {
    const dataSources = this.getDataSources();
    dataSources.forEach(item => {
      const id = item._id;
      if (this.ma.indexOf(id) >= 0) {
        this.widget.chart()._chartWidget._model.removeSource(item);
      }
    });
  }

  render() {
    // this.dom.menu.each((index, item) => {
    //   this.$(item).text(this.$(item).attr("title"));
    // });
  }

  debounce(fn, interval) {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      fn();
    }, interval);
  }

  getChartType() {
    return this.widget.chart().chartType();
  }

  hideMaLine() {
    this.delMa();
  }

  showMaLine() {
    this.widget.chart().createStudy("Moving Average", false, false, [5]);
    this.widget.chart().createStudy("Moving Average", false, false, [10]);
    this.widget.chart().createStudy("Moving Average", false, false, [30]);
    this.widget.chart().createStudy("Moving Average", false, false, [60]);
  }

  //隐藏 暂时用不到 没有测试
  hideMenu() {
    this.panelHeaderIns._interval._menu.close();
  }

  //禁止menu.close方法
  //为了不让别的事件关闭menu，禁止他的close方法
  rmMenuClose() {
    this.panelHeaderIns._interval._menu.close = function() {};
  }

  //显示时间选择器
  showMenu() {
    this.panelHeaderIns._interval._menu.open(
      this.panelHeaderIns._interval.getSortedIntervals()
    );
  }

  setBtnSelected(dom) {
    this.$(dom)
      .addClass("on")
      .siblings("span")
      .removeClass("on");
  }

  rmBtnSelected(dom) {
    this.$(dom).removeClass("on");
  }

  hideMa() {
    this.widget
      .chart()
      .getAllStudies()
      .map(item => {
        if (item.name == "Moving Average") {
          const ma = this.widget.chart().getStudyById(item.id);
          ma.setVisible(false);
        }
      });
  }

  showMa() {
    this.widget
      .chart()
      .getAllStudies()
      .map(item => {
        if (item.name == "Moving Average") {
          const ma = this.widget.chart().getStudyById(item.id);
          ma.setVisible(true);
        }
      });
  }

  addListen() {
    this.dom.menu.on("click", e => {
      this.showMa();
      this.rmBtnSelected(this.dom.timeShareBtn);
      //k线图
      this.widget.chart().setChartType(STYLET_YPE.candles);
      this.$(e.target).addClass("selected");
    });
    this.$(this.dom.timeShareBtn).on("click", e => {
      this.setBtnSelected(e.target);
      this.widget.chart().setResolution("1"); //1分钟
      this.widget.chart().setChartType(3); //type为3  是面积图（可以省略此行）
      this.hideMa();
      const timer = setTimeout(() => {
        this.dom.menu.removeClass("selected");
        clearTimeout(timer);
      }, 0);
    });
  }
}

export class WidgetStyle {
  constructor(props) {
    this.widgetStyleIns = null;
    this.lists = null;
    this.props = null;
    this.props = props;
    this.init();
  }

  init() {
    this.initIns();
    this.initLists();
    // this.setOn(STYLET_YPE.area);
  }

  initIns() {
    this.widgetStyleIns = this.props.panelHeaderIns._style_list;
  }

  initLists() {
    this.lists = this.widgetStyleIns._data;
  }

  getItem(v) {
    return this.widgetStyleIns._getItemByValue(v);
  }

  setOn(v) {
    const item = this.getItem(v);

    this.widgetStyleIns._onSelect.fire(item.data.id);
    this.widgetStyleIns._setActive(item);
    this.widgetStyleIns._onChange.fire(item.data.id);
  }
}
